﻿using System;
using System.Linq;
using System.ComponentModel;
using System.Windows;
using System.Windows.Interactivity;
using System.Collections;
using System.Collections.Generic;
#if WP7
using nRoute.Behaviors.Interactivity;
#endif

namespace nRoute.Samples.Netflix.Behaviors
{
    public class CountVisibilityBehavior
#if WP7
        : BindableBehavior<FrameworkElement>
#else
        : Behavior<UIElement>
#endif
    {
        public static readonly DependencyProperty ValueProperty =
            DependencyProperty.Register("Value", typeof(IEnumerable), typeof(CountVisibilityBehavior),
            new PropertyMetadata(Utilities.Compatability.DP_UNSET_VALUE, new PropertyChangedCallback(OnValueChanged)));

        private bool _negate;

#region Properties

        [Category("Common Properties")]
        public IEnumerable Value
        {
            get { return (IEnumerable)GetValue(ValueProperty); }
            set { SetValue(ValueProperty, value); }
        }

#if WP7

        [Category("Common Properties")]
#if (!WP7)
        [CustomPropertyValueEditor(CustomPropertyValueEditor.PropertyBinding)]
#endif
        public Binding ValueBinding
        {
            get { return GetBinding(ValueProperty); }
            set { SetBinding<bool>(ValueProperty, value); }
        }

#endif

        [Category("Common Properties")]
        public bool Negate
        {
            get { return _negate; }
            set { _negate = value; }
        }

#endregion

#region Trigger Related

        protected override void OnAttached()
        {
            base.OnAttached();
            UpdateVisibility(Value);
        }

#endregion

#region Handlers

        private static void OnValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ((CountVisibilityBehavior)d).UpdateVisibility((IEnumerable)e.NewValue);
        }

        private void UpdateVisibility(IEnumerable value)
        {
            if (this.AssociatedObject == null) return;

            var _count = (value == null) ? 0 : value.Cast<Object>().Count();    // bad?
            var _visibility = _count == 0 ? Visibility.Collapsed : Visibility.Visible;
            if (Negate) _visibility = (_visibility == Visibility.Visible) ? Visibility.Collapsed : Visibility.Visible;
            this.AssociatedObject.Visibility = _visibility;
        }

#endregion

    }
}
